import requests  
import sys  
import os  
import json  
import time  
import pickle  
from bilibili_api import login, user, sync
from bilibili_api.user import HistoryType

class Coach:
    def __init__(self):
        self.session_request_result_state = False
        self.sessdata = None
        # Bilibili API login
        self.credential = None
    def get_session_key_file(self) -> bool:
        # 定义JSON文件的名称  
        json_file_name = 'cookie.json'  
        # 检查文件是否存在  
        if os.path.exists(json_file_name):  
            # 读取文件内容  
            with open(json_file_name, 'r', encoding='utf-8') as file:  
                data = json.load(file)  # 解析JSON文件  
            # 尝试获取SESSDATA字段  
            if 'SESSDATA' in data:  
                self.sessdata = data['SESSDATA']  
                # print(f"SESSDATA: {self.sessdata}")  
                return True
        else:  
            print(f"文件 {json_file_name} 不存在。")
            return False
    def get_cookie_session_key(self,force : bool = False):
        if force == True:
            self.session_request_result_state = libs.bilibili_qrcode_login.utils.save_json_file(path="./cookie.json", data=libs.bilibili_qrcode_login.login.get_cookie())
        if self.get_session_key_file() == False:
            self.session_request_result_state = libs.bilibili_qrcode_login.utils.save_json_file(path="./cookie.json", data=libs.bilibili_qrcode_login.login.get_cookie())
    def get_suggestion_video(self):
        # 填充你的Cookie，特别是SESSDATA  
        cookies = {  
            'SESSDATA': self.sessdata,  
        }  
        
        # 设置请求参数  
        params = {  
            'fresh_type': 4,  
            'ps': 12,  
            'fresh_idx': 5,  
            'fresh_idx_1h': 5,  
            'fetch_row': 16,  
        }  
        
        # 发送GET请求  
        url = 'https://api.bilibili.com/x/web-interface/wbi/index/top/feed/rcmd'  
        response = requests.get(url, params=params, cookies=cookies)  
        
        # 打印响应内容  
        print(response.json())
    def process_history(self,history_list):  
        for item in history_list:  
            print('Title:', item['title'])  
            print('View Time:', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(item['view_at'])))  
            print('Progress:', item['progress'], 'seconds')  
            print('-' * 30)  
    # 异步获取用户浏览历史记录的函数  
    def fetch_user_history(self,view_at = None,max = None) -> 'dict':  
        try:  
            history = sync(user.get_self_history_new(  
                self.credential,  
                _type=HistoryType.ALL,   
                ps=20,  
                view_at = view_at,
                max = max
            ))  
            return history
        except Exception as e:  
            print(f"获取历史记录时发生错误：{e}")  
    def check_credential_pickle_exists(self, filename='credential.pickle'):  
        """  
        检查指定名称的pickle文件是否存在。  
    
        参数:  
        - filename: pickle文件的名称，默认为'credential.pickle'。  
    
        返回:  
        - 如果文件存在，则返回True；否则返回False。  
        """  
        return os.path.isfile(filename) 
    def save_credential_local(self, credential) -> None:
        # 将 credential 对象保存到文件  
        with open('credential.pickle', 'wb') as f:  
            pickle.dump(credential, f)
    def load_credential_local(self) -> None:
        # 从文件读取 credential 对象  
        with open('credential.pickle', 'rb') as f:  
            self.credential = pickle.load(f)  
    def login(self) -> None:
        # 使用示例  
        if self.check_credential_pickle_exists():  
            print("找到保存的credential pickle文件。")  
            self.load_credential_local()
            self.credential.raise_for_no_bili_jct() # 判断是否成功
            self.credential.raise_for_no_sessdata() # 判断是否成功
            print("Get credential success")
        else:  
            print("未找到保存的credential pickle文件。")
            print("请登录：")
            self.credential = login.login_with_qrcode_term() # 在终端扫描二维码登录
            try:
                self.credential.raise_for_no_bili_jct() # 判断是否成功
                self.credential.raise_for_no_sessdata() # 判断是否成功
                print("Get credential success")
                print("Saving credential")
                self.save_credential_local(self.credential)
            except:
                print("登陆失败。。。")
    def get_user_info(self):
        name = sync(user.get_self_info(self.credential))['name']
        print("欢迎，", name, "!")